package org.zjt.lock;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class BlockQueue<T> {
    private final int size ;
    private final List<T> list = new ArrayList<>();

    public BlockQueue(int size) {
        this.size = size;
    }

    public synchronized void put(T t) throws InterruptedException {
        while (list.size() >= size){
            this.wait();
        }
        this.list.add(t);
        Thread.sleep(Math.abs(new Random().nextInt()) % 1000);
        this.notify();
    }

    public synchronized T get() throws InterruptedException {
        while (list.isEmpty()){
            this.wait();
        }
        T t = this.list.remove(0);
        Thread.sleep(Math.abs(new Random().nextInt()) % 1000);
        this.notify();
        return t;
    }

    public static void main(String[] args) throws InterruptedException {
        BlockQueue<Object> queue = new BlockQueue(10);
        new Thread(() -> {
            Arrays.asList(1,2,3,2,32,3,32,3,"sds",7878).stream().forEach(
                    item -> {
                        try {
                            queue.put(item);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    });
        }).start();

        new Thread(() -> {
            for (;;){
                try {
                    System.out.println(queue.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        Thread.sleep(10000000);
    }
}
